package com.good.jzhouse.controller;

import com.alibaba.fastjson.JSON;
import com.good.jzhouse.bean.*;
import com.good.jzhouse.dao.GolerecordDao;
import com.good.jzhouse.dao.MenuDao;
import com.good.jzhouse.dao.MessageDao;
import com.good.jzhouse.dao.UsersDao;
import com.good.jzhouse.tools.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/backer")
public class UsersController {

    @Resource
    UsersDao ud;
    @Resource
    GolerecordDao golerecordDao;
    @Resource
    MenuDao md;
    @Autowired
    MessageDao messageDao;


    @RequestMapping("/login")
    @ResponseBody
    public Users login(Users u, HttpSession session, Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(u.getUserId(),u.getPassword());
        Users u2 = ud.selectByPrincipal(u.getUserId());
        session.setAttribute("user",u2);
        try {
            System.out.println(token.getPrincipal());
            subject.login(token);
            session.setAttribute("user",u2);
            return u2;
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!");
            return null;

        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误!");
            return  null;
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpSession s){
        List<Integer> qd = (List<Integer>) s.getAttribute("qd");
        SecurityUtils.getSubject().logout();
        SecurityUtils.getSubject().getSession().setAttribute("qd",qd);
        return "login";
    }

    @RequestMapping("/checkPhoneNumber")
    @ResponseBody
    public boolean checkPhoneNumber(String phone){
        if (ObjectUtils.isEmpty(ud.selectByPhone(phone))){
            return true;
        }else{
            return false;
        }
    }
    @ResponseBody
    @RequestMapping("/register")
    public String register(Users u,String yzm,HttpSession session){
        Message message;
        System.out.println("进行注册");
        if(!ObjectUtils.isEmpty(message = messageDao.selectByPhone(u.getPhone()))){  //如果验证码发送成功
            //提交注册的时间
            Long now =new Date().getTime();
            //验证码发送的时间
            Long sendTime = message.getSendTime().getTime();
            if(now - sendTime < (1000*600)){        //相差时间小于10分钟
                if(StringUtils.hasText(yzm) && message.getCode().equals(yzm)){       //客户端验证码不为空 且和后台的验证码相同
                    u.setBalance(0.0);
                    u.setCommunityName("买房新人");
                    u.setCreateDate(new Timestamp(new Date().getTime()));
                    u.setGold(0);
                    u.setLastLoginTime(new Timestamp(new Date().getTime()));
                    u.setRole(new Role(2,null));
                    u.setIntegral(0);
                    u.setPicture("zs.jpg");
                    u.setPassword(Md5Util.MD5Pwd(u.getPassword(),u.getPhone()));    //MD5加密
                    //插入数据
                    int success = ud.register(u);
                    if (success>0){
                        return "注册成功！";
                    }else {
                        return "注册失败，稍后重试";
                    }

                }else {
                    System.out.println("前台提交验证码：" +yzm);
                    System.out.println("后台比对验证码：" +message.getCode());
                    return  "意外错误！验证码无效";
                }

            }else{
                //验证码超时
                return  "验证码超时,请重新发送!";
            }

        }else {
            //验证码发送失败
            return "验证码发送失败,请稍后重试!";
        }

    }




    @RequestMapping("/syshomepage")
    public String syshomepage(){
        return "SysHomePage";
    }

    @RequestMapping("/sellinfo")
    public String Sellinfo(){
        return "SellInfo";
    }

    @RequestMapping("/leaseInfo")
    public String LeaseInfo(){
        return "LeaseInfo";
    }

    @RequestMapping("/wanttobuyinfo")
    public String wanttobuyinfo(){
        return "wanttobuyinfo";
    }

    @RequestMapping("/askingtorankinfo")
    public String askingtorankinfo(){
        return "askingtorankinfo";
    }

    @RequestMapping("/menberInfo")
    public String MenberInfo(){
        return "MenberInfo";
    }

    @RequestMapping("/memberUpgrade")
    public String MemberUpgrade(){
        return "MemberUpgrade";
    }

    @RequestMapping("/rechargeCenter")
    public String RechargeCenter(){
        return "RechargeCenter";
    }

    @RequestMapping("/usersList")
    public String UsersList(){
        return "UsersList";
    }

    @RequestMapping("/houseRental")
    public String HouseRental(){
        return "HouseRental";
    }

    @RequestMapping("/houseForSale")
    public String HouseForSale(){
        return "HouseForSale";
    }

    @RequestMapping("/buyHouse")
    public String buyHouse(){
        return "BuyHouse";
    }

    @RequestMapping("/rentHouse")
    public String RentHouse(){
        return "RentHouse";
    }

    @RequestMapping("/user")
    public String list(Model model, HttpSession session) throws UnknownHostException {
        Users user = (Users) session.getAttribute("user");
        InetAddress address = InetAddress.getLocalHost();
        String ip = address.getHostAddress();
        session.setAttribute("ip",ip);
        model.addAttribute("menu",md.SelectMenu(user.getRole().getRoleid()));
        return "UserCenter";
    }

    @RequestMapping("/syspage")
    @ResponseBody
    public Users list2(Model model, HttpSession session){
        Users users = (Users) session.getAttribute("user");
        return  users;
    }

    @RequestMapping("/userslist")
    @ResponseBody
    public String userlist(Integer page,Integer limit){
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",ud.count());
        map.put("data",ud.selectLimit((page-1)*limit,limit));
        return JSON.toJSONStringWithDateFormat(map,"yyyy-MM-dd");
    }

    @GetMapping("/SelectMenu/{roleId}")
    @ResponseBody
    public List<Menu> SelectMenu(@PathVariable("roleId") Integer roleId,HttpSession session){
        Users users = (Users) session.getAttribute("user");
        return md.SelectMenu(users.getRole().getRoleid());
    }

    @RequestMapping("/isdiff")
    @ResponseBody
    public Boolean isdiff(String oldpwd,HttpSession session) {
        /* Md5Util.MD5Pwd(oldpwd,"1024");*/
        Users user = (Users) session.getAttribute("user");
        System.out.println("--------------oldpwd:" + oldpwd);
        System.out.println("-------------password:" + user.getPassword());
        System.out.println("--------------MD5"+Md5Util.MD5Pwd(oldpwd,user.getPhone()));
        if (user.getPassword().equals(Md5Util.MD5Pwd(oldpwd,user.getPhone()))) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("useredit")
    @ResponseBody
    public Boolean ue(Users users,String pwd,HttpSession session){
        String imgpath = (String) session.getAttribute("userimgPaths");
        if(users.getPassword()=="")users.setPassword(pwd);
        users.setPassword(Md5Util.MD5Pwd(users.getPassword(), users.getPhone()));
        if(imgpath!=null){
            users.setPicture(imgpath);
            session.setAttribute("userimgPaths",null);
        }
        if(ud.edit(users)>0) {
            Users u = ud.selectById(users.getUid());
            session.setAttribute("user",ud.selectByUserIdAndPwd(u.getUserId(),u.getPassword()));
            return true;
        }else{
            return  false;
        }
    }

    @ResponseBody
    @RequestMapping("/modifygold")
    public Boolean ug(Integer gold,Integer integral,Double balance,Integer id,HttpSession session){
        Users u = (Users)session.getAttribute("user");
        List<Integer> qd = (ArrayList<Integer>) session.getAttribute("qd");
        if(qd==null){
            qd = new ArrayList<Integer>();
            qd.add(u.getUid());
        }else{
            qd.add(u.getUid());
        }
        session.setAttribute("qd",qd);

        Golerecord g = new Golerecord();
        Date d = new Date();
        Timestamp t = new Timestamp(d.getTime());
        g.setUpdateTime(t);
        g.setUser(u);
        g.setGoldRemark("用户签到+1");
        g.setNumberChange("积分+1");
        if(golerecordDao.insert(g)>0 && ud.updategold(u.getGold()+1,u.getIntegral()+1,u.getUid())>0){
            return true;
        }
        return false;
    }

}
